package com.zxh.blog.web;

import com.zxh.blog.domain.User;
import com.zxh.blog.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {

	@Autowired
	UserService userService;

	@RequestMapping(value = "doLogin",method = RequestMethod.POST)
	@ResponseBody
	public Map doLogin(HttpServletRequest request){
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		User user = userService.findUserByUserName(userName);
		UsernamePasswordToken token = new UsernamePasswordToken(userName,password);
		HashMap<String,String> map = new HashMap<String,String>();
		try {
			request.getSession().setAttribute("userName",userName);
			request.getSession().setAttribute("userId",user.getId());
			SecurityUtils.getSubject().login(token);
			map.put("result","success");
			return map;
		} catch (AuthenticationException e) {
			e.printStackTrace();
		}
		map.put("result","fail");
		return map;
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public void logout(HttpServletRequest request) {
		// shiro退出登录
		SecurityUtils.getSubject().logout();
		// 跳回原地址
//		String redirectUrl = request.getHeader("Referer");
//		if (null == redirectUrl) {
//			redirectUrl = "/";
//		}
//		return "redirect:" + redirectUrl;
	}

	@RequestMapping(value = "currentUser",method = RequestMethod.GET)
	@ResponseBody
	public Map currentUser(HttpServletRequest request){
		String userName = (String) request.getSession().getAttribute("userName");
		HashMap<String, Object> map = new HashMap();
		map.put("userName",userName);
		map.put("userId",request.getSession().getAttribute("userId"));
		return map;
	}
}
